<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '#' }">
        运动会报名信息管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="#">运动员登录</a>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="sp-card">
      <div class="top">
        <el-form style="width: 270px;">
          <el-form-item label="单位：">
            <el-select v-model="pictunit" filterable>
              <el-option v-for="item in selUnitData" :key="item.tiid" :label="item.tname"
                :value="item.tiid"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="top_add">
          <el-button type="warning" @click="adddialogVisible = true">添加</el-button>
        </div>
        <div class="excel_btn">
          <el-button type="primary" @click="leadFileVisible2 = true">郑州游泳考试导入</el-button>
          <el-button type="primary" @click="sampleExportExcel">样本导出</el-button>
          <el-button type="primary" @click="leadFileVisible = true">导入</el-button>
          <el-button type="primary" @click="exportExcel">导出</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="spoData" border stripe>
        <el-table-column prop="plno" label="编号" width="60">
        </el-table-column>
        <el-table-column prop="name" label="姓名">
        </el-table-column>
        <el-table-column prop="sexName" label="性别">
        </el-table-column>
        <el-table-column prop="gridName" label="组别">
        </el-table-column>
        <el-table-column prop="regdate" label="报名日期">
          <template #default="scope">
            {{ formattedDateTime(scope.row.regdate) }}
          </template>
        </el-table-column>
        <el-table-column prop="zhucehao" label="注册号">
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button type="success" @click="viewselItemdialog(scope.row)">查看</el-button>
            <el-button type="primary" @click="showeditdialog(scope.row)">修改</el-button>
            <el-button type="danger" @click="spodelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="paging" @size-change="handleSizeChange" @current-change="handleSizeChange" background
        :page-sizes="[3, 5, 10, 15, 20, 50]" layout="total,prev, pager, next, jumper" :total="total"
        :page-size="queryObj.pageSize" :current-page="queryObj.pageNum">
      </el-pagination>

      <!-- 导入 -->
      <el-dialog title="导入" v-model="leadFileVisible" width="20%" draggable>
        <input type="file" class="dialog-inp" @change="athletesFileUpload">
        <div slot="footer" class="dialog-footer">
          <el-button @click="leadFileVisible = false">取 消</el-button>
          <el-button type="primary" @click="uploadFile">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="导入" v-model="leadFileVisible2" width="20%" draggable>
        <input type="file" class="dialog-inp" @change="athletesFileUpload2">
        <div slot="footer" class="dialog-footer">
          <el-button @click="leadFileVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="textFile">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 修改页面 -->
      <el-dialog class="edit_dialog" title="运动员登陆修改" v-model="editdialogVisible" draggable width="40%"
        :before-close="handleClose">
        <el-form :model="editfrom" label-width="120">
          <el-form-item label="序号：">
            <el-input v-model="editfrom.plno"></el-input>
          </el-form-item>
          <el-form-item label="姓名：">
            <el-input v-model="editfrom.name"></el-input>
          </el-form-item>
          <el-form-item label="性别：">
            <el-select v-model="editfrom.sex">
              <el-option v-for="item in sexData" :key="item.sex" :label="item.sxname" :value="item.sex"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出生日期：">
            <el-date-picker v-model="editfrom.birth" value-format="YYYY-MM-DD" type="date" placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="组别：">
            <el-select v-model="editfrom.grid">
              <el-option v-for="item in groupData" :key="item.grid" :label="item.name" :value="item.grid"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="注册码：">
            <el-input v-model="editfrom.zhucehao"></el-input>
          </el-form-item>
          <el-form-item label="报名日期：">
            <el-date-picker v-model="editfrom.regdate" value-format="YYYY-MM-DDTHH:mm:ss" type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelEdit">取 消</el-button>
          <el-button type="primary" @click="editSportsigeinfo">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 新增页面 -->
      <el-dialog class="add_dialog" title="运动员登陆添加" v-model="adddialogVisible" draggable width="40%"
        :before-close="addleClose">
        <el-form :model="addfrom" label-width="120" :rules="rules" ref="addForm">
          <el-form-item prop="plno" label="序号：">
            <el-input v-model="addfrom.plno"></el-input>
          </el-form-item>
          <el-form-item prop="name" label="姓名：">
            <el-input v-model="addfrom.name"></el-input>
          </el-form-item>
          <el-form-item label="性别：">
            <el-select v-model="addfrom.sex">
              <el-option v-for="item in sexData" :key="item.sex" :label="item.sxname" :value="item.sex"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出生日期：">
            <el-date-picker v-model="addfrom.birth" value-format="YYYY-MM-DD" type="date" placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="组别：">
            <el-select v-model="addfrom.grid">
              <el-option v-for="item in groupData" :key="item.grid" :label="item.name" :value="item.grid"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="注册码：">
            <el-input v-model="addfrom.zhucehao"></el-input>
          </el-form-item>
          <el-form-item prop="regdate" label="报名日期：">
            <el-date-picker v-model="addfrom.regdate" value-format="YYYY-MM-DDTHH:mm:ss" type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addleClose">取 消</el-button>
          <el-button type="primary" @click="addSpo">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 查看页面 -->
      <el-dialog title="运动员详细信息" v-model="datailsdialogVisible" draggable width="50%">
        <el-table :data="datailsData" border stripe>
          <el-table-column label="选择" width="80">
            <template #default="scope">
              <el-checkbox v-model="scope.row.mflag" :true-label="1" :false-label="0"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="msidName" label="项目">
          </el-table-column>
          <el-table-column prop="msrec" label="报名成绩">
          </el-table-column>
          <el-table-column label="测验" width="80">
            <template #default="scope">
              <el-checkbox :disabled="scope.row.mflag === 0" v-model="scope.row.mstype" :true-label="1"
                :false-label="0"></el-checkbox>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="datailsdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSportsigeinfo">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import { ElLoading } from 'element-plus'
export default {
  components: {
    XLSX,
  },
  data() {
    return {
      selUnitData: [],
      sexData: [],
      groupData: [],
      pictunit: null,
      queryObj: {
        pageSize: 10,
        pageNum: 1,
        query: " "
      },
      total: 0,
      spoData: [],
      // 导入
      leadFileVisible: false,
      leadFileVisible2: false,
      adddialogVisible: false,
      addfrom: {
        tiid: null,
        plno: null,
        name: '',
        sex: null,
        birth: '',
        grid: null,
        zhucehao: '',
        regdate: ''
      },
      initialForm: {},
      editdialogVisible: false,
      editfrom: {},
      // 查看
      datailsdialogVisible: false,
      datailsData: [],
      formData: null,
      formData2: null,
      targetObject: '',
      rules: {
        plno: [
          { required: true, message: '请输入序号', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        regdate: [
          { required: true, message: '请选择报名日期', trigger: 'change' },
        ],
      }
    }
  },
  created() {
    this.initialForm = { ...this.addfrom }
    this.getComunitinfoList();
    this.getSexinfoList();
    this.getGroupinfoList();
  },
  methods: {
    // 查询
    async getComunitinfoList() {
      const result = await this.$http.get(this.BACKEND_URL + '/team/getmsg');
      if (result.data.code == 0) {
        this.selUnitData = result.data.data
        this.pictunit = this.selUnitData[0].tiid
        this.getSportsigeinfoList(this.pictunit)
        this.selUnitData.sort((a, b) => a.tiid - b.tiid)
      } else if (result.data.code == 500) {
        console.log(result.data.msg)
      }
    },
    async getSportsigeinfoList(tiid) {
      try {
        const result = await this.$http.get(this.BACKEND_URL + '/athletes/getmsg', {
          params: {
            tiid: tiid,
            pageSize: this.queryObj.pageSize,
            pageNum: this.queryObj.pageNum,
          }
        });
        console.log(result)
        if (result.data.code == 0) {
          this.spoData = result.data.data
          this.spoData.sort((a, b) => a.plno - b.plno)
          this.total = result.data.total
        } else if (result.data.code == 500) {
          this.spoData = []
          console.log(result.data.msg)
        }
      } catch (error) {
        if (error === undefined) {
          this.$message.error('连接错误-获取数据失败');
        }
      }
    },
    async getSexinfoList() {
      const result = await this.$http.post(this.BACKEND_URL + '/match/getmsg');
      if (result.data.code == 0) {
        this.sexData = result.data.data
      } else if (result.data.code == 500) {
        console.log(result.data.msg)
      }
    },
    async getGroupinfoList() {
      const result = await this.$http.post(this.BACKEND_URL + '/match/getGroupmsg');
      if (result.data.code == 0) {
        this.groupData = result.data.data
      } else if (result.data.code == 500) {
        console.log(result.data.msg)
      }
    },
    formattedDateTime(val) {
      return val.replace("T", " ")
    },
    // 删除单条数据
    spodelete(e) {
      this.$confirm('此操作将删除改条数据，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        const result = await this.$http.post(this.BACKEND_URL + '/athletes/deletemsg', e)
        if (result.data.code === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getSportsigeinfoList(this.pictunit);
        } else if (result.data.code == 500) {
          this.$message.error(result.data.msg)
        }
      }).catch(() => {
      });
    },
    // 修改,获取单个数据信息
    showeditdialog(info) {
      this.editdialogVisible = true
      this.editfrom = info
    },
    async editSportsigeinfo() {
      const result = await this.$http.post(this.BACKEND_URL + '/athletes/updatemsg', this.editfrom)
      console.log(result)
      if (result.data.code == 0) {
        this.editdialogVisible = false
        this.datailsdialogVisible = false
        this.getSportsigeinfoList(this.pictunit);
        this.$message.success('修改成功')
      } else if (result.data.code == 500) {
        this.getSportsigeinfoList(this.pictunit);
        this.$message.error(result.data.msg)
      }
    },
    // 获取查看数据
    viewselItemdialog(val) {
      this.editfrom = val
      this.datailsdialogVisible = true
      this.datailsData = val.stylesList
      this.datailsData.sort((a, b) => a.msid - b.msid)
    },
    // 新增数据
    async addSpo() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          const result = await this.$http.post(this.BACKEND_URL + '/athletes/insertmsg', this.addfrom)
          if (result.data.code == 0) {
            this.adddialogVisible = false
            this.getSportsigeinfoList(this.pictunit);
            this.$message.success('添加成功')
            this.addfrom = { ...this.initialForm }
          } else if (result.data.code == 500) {
            this.addfrom = { ...this.initialForm }
            this.$message.error(result.data.msg)
          }
        } else {
          this.$message.error('请填写必要信息');
        }
      });
      this.addfrom.tiid = this.pictunit

    },
    addleClose() {
      this.adddialogVisible = false
      this.addfrom = { ...this.initialForm }
    },
    cancelEdit() {
      this.editdialogVisible = false
      this.getSportsigeinfoList(this.pictunit);
    },
    handleClose(done) {
      this.getSportsigeinfoList(this.pictunit)
      done()
    },
    // 导入
    athletesFileUpload(e) {
      let file = e.target.files[0]
      this.formData = new FormData()
      this.formData.append('file', file);
    },
    async uploadFile() {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      const result = await this.$http.post(this.BACKEND_URL + '/athletes/excel', this.formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      if (result.data.code == 0) {
        loading.close();
        this.leadFileVisible = false
        this.getComunitinfoList()
        this.$message({
          type: 'success',
          message: '导入成功!'
        });
      } else if (result.data.code == 500) {
        loading.close();
        this.$message({
          type: 'error',
          message: '导入失败!'
        });
        console.log(result.data.msg)
      }
    },
    // 郑州项目导入
    athletesFileUpload2(e) {
      let file2 = e.target.files[0]
      this.formData2 = new FormData()
      this.formData2.append('file', file2);
    },
    async textFile() {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      const result = await this.$http.post(this.BACKEND_URL + '/import/excel', this.formData2, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      if (result.data.code == 0) {
        loading.close();
        this.leadFileVisible2 = false
        this.getComunitinfoList()
        this.$message({
          type: 'success',
          message: '导入成功!'
        });
      } else if (result.data.code == 500) {
        loading.close();
        this.$message({
          type: 'error',
          message: '导入失败!'
        });
        console.log(result.data.msg)
      }
    },
    // 样本导出-表格
    async sampleExportExcel() {
      try {
        const response = await this.$http.get(this.BACKEND_URL + '/athletes/exportmole', {
          responseType: 'blob',
        });

        let downloadUrl = window.URL.createObjectURL(new Blob([response.data]));

        const link = document.createElement('a');
        link.href = downloadUrl;
        link.setAttribute('download', '样本表S.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error('File export failed:', error);
      }
    },
    // 表格+数据导出
    async exportExcel() {
      for (let i = 0; i < this.selUnitData.length; i++) {
        if (this.selUnitData[i].tiid === this.pictunit) {
          this.targetObject = this.selUnitData[i].tname
        }
      }
      try {
        const response = await this.$http.get(this.BACKEND_URL + '/athletes/export', {
          params: { tiid: this.pictunit },
          responseType: 'blob',
        });

        let downloadUrl = window.URL.createObjectURL(new Blob([response.data]));

        const link = document.createElement('a');
        link.href = downloadUrl;
        link.setAttribute('download', this.targetObject + '运动员S.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error('File export failed:', error);
      }
    },
    // 分页
    handleSizeChange(newSize) {
      this.queryObj.pageNum = newSize
      this.getSportsigeinfoList(this.pictunit);
    }
  },
  watch: {
    pictunit(newGroupName, oldGroupName) {
      if (newGroupName !== oldGroupName) {
        this.getSportsigeinfoList(newGroupName);
      }
    },
    'datailsData': {
      handler: function (val) {
        val.forEach(row => {
          if (row.mflag === 0) {
            row.mstype = 0
          }
        });
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
:deep(.el-date-editor.el-input) {
  width: 100%;
}

// 顶部
.top {
  display: flex;
}

.top_add {
  margin-left: 10px;
}

.excel_btn {
  text-align: right;
  flex: 1;
}

.sp-card {
  margin-top: 15px;
}


:deep(.cell) {
  text-align: center;
}

.dialog-footer {
  margin-top: 15px;
}

.edit_dialog {
  .el-select {
    width: 100%;
  }
}

.add_dialog {
  .el-select {
    width: 100%;
  }
}

.dialog-inp {
  border: 1px solid #ccc;
}

.paging {
  margin-top: 15px;
}
@media (max-width:916px) {
  .top{
    flex-wrap: wrap;
  }
}
</style>
